package com.ruoyi.web.service.pay;

import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Service
public class AlipayService {

    public static String APPID = "2021005121644709";
    public static String RSA_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJo3ZhqlyfoeVcs98Lw4E48ytocYJ1nFdmqV7ukD+gFj6PGdbdzW1pf/Kz7ZKxnVUDiYhSdV7sMWxnpmPKRZDNuk15hBrnbLalKF+5i0rH4JJY9n1msbXfIe6L7z0o4dsehoqTJlMOb74KkvbhWc2fNq7/BsZhrA3GK1Y9oAiBv7c+vxYZC66L01sJmmE1oQvYl0oE5D3+jOw9zBLpmw1yGdzUIp8iKaNJb7eLU8Xg2SfCYKe29xMkDlkLiwLQj0JQY5QXTNclmbFTVIEqnk8Tq7xWFHuo0s2v3aNOn2QhkioSuS0yroNckDzttVliBSEPD4Oql9pIPt3ejdHonMRZAgMBAAECggEAUrEgmIDP8SBFOrLeWKT26A5AkBlSNfLeF9G+NTn43+c9YqA1lUCscWvrluou7gMGZn+kpVXa17DB3mv7HDU7UD6T+WPC/jM0cHmXOVRUc02a31QH90DhcdNjDDOJ3RwEl4xhiRLHZ67+0D+Hj9ByVyt1a8bYPSovhFXZFGEnezuf20RbvD8VgS0Xmlm1KkhjVSd6hmNTqBbLAllcd7+GLuegymdbctDRdbSeHfa2RL5Nn11wWNJt6CEi24uh70gwW2Dn7WWzlpHBVWrpJyER+ZcWkdryOFjuw9dX8MPh2MxuN2kB9wIhEoAWVY7H1NItpHg7WEp3Q6VrgqqxPvu7eQKBgQDCljFXJfJZUmpVBWYA9N3EcVxY6MQAnjZ4qn16H4ZOEQrllgf0OH34ZiREWzp7UsunJsB4TlYZyR5ooTPTcdYC+IPPWaI/b1uSJX6keWHhjfEzMZP+ucgHxKupifY44i+n7jc/VaQnSoizytkoHzTvaX9QtbrbahBgFHcLC49dIwKBgQC1FBdeVGLHQBPBI/awxU944nI4yTrEQKHaBcmXeAQXLQ8FEKtBKspXTEWCLVmDl4Cotn8/yprsNH37pV+QC41qO0wUSAatUmtFRY1dJAQ7hQUBeIv05UuCpYWQSHcqnnbxesp0Kd1T9xQhctMOECbLVLindumco4FeQV5p505GUwKBgCOotn4L/C+WRNoz1Q+T0Bgx1gSNE24xkDXouHnq0Qf5Y4/TQL3mpF8jCL5mIX98GsoU9eyWHn03OBVghUjYcam1tSIIgQ0y8QsFSAIIJIHbKzqAeWiSzy9tQTAekjq2aJlTtFgs75ortIWOROFvZpoBMU2vIAEZnMqetXoWsj0VAoGAGykGUEnL/yLnU6L3T5Bo2TLt+wKD5AflvvP7RtLjmi5SAGp9pWqrquhvzJTMxmYlECk/cOwMzL0a4HHvoYV6EqMOSER9a+Xe3ScPixbp45uSIqRYKcVyzAfTvs5/wU6/fHz0fPQClKOMy2+TpJpbl0f/4m59n9cOgnq/lJbzMK0CgYEAooT/CRGQFwjRIMKZbRnSS+Mb6AZJFlL6PRAcNQDKGaCVd3eqLjSKNXaiKKqXVfYKiuV7K7/VkKOVkiiuX5oa3h5VDUS2OZZJNV1QhtTBFMkNMkaau4LKk0su9Z6TVSNgImS33ydt87pOf7DfneHxjMDjjgrLznaspJHGJOsX7ek=";
    public static String URL = "https://openapi.alipay.com/gateway.do";
    public static String CHARSET = "UTF-8";
    public static String FORMAT = "json";
    public static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiwdNo+3AXpu8vuaqzmC8H2LkSyAKdMS81PaqJWHF1p9jbxlOB4XoChGltKbsdhw22x27uu4ya27DO+p5Te7OrO3pjb+v3myvRfLVvndokFKeWwVK3KYgCqf9uBHVAuNFlKH40ksJLjPbgZFquv+IPaMbKqrWir+CpBQoHEeYXK2yy+bhm6ANLev9ysH0BLUg/J+VwHFQWkGTpfh9Mi5IJ/XS7IYa3S7S/i27BqxzY4Dqx7udQVfH3j/1FZgWVtmD8IGtv2Cd5BXP6yIdpCR3tZPgWrQ5SxwDssbFZPwVJLhMVMYRPVyTVEH+uZbxXIhHon5HhAXw3XFDA4V8102ekQIDAQAB";
    public static String SIGNTYPE = "RSA2";

    public static String creatOrder(Map<String, String> params) {
        String orderString = "";
        try {
            DefaultAlipayClient defaultAlipayClient = new DefaultAlipayClient(URL, APPID, RSA_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGNTYPE);
            AlipayTradeAppPayRequest alipayTradeAppPayRequest = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setBody(params.get("body"));
            model.setSubject(params.get("subject"));
            model.setOutTradeNo(params.get("tradeNo"));
            model.setTimeoutExpress("40m");
            model.setProductCode("QUICK_MSECURITY_PAY");
            model.setTotalAmount(params.get("amount"));
            alipayTradeAppPayRequest.setBizModel((AlipayObject) model);
            alipayTradeAppPayRequest.setNotifyUrl(params.get("notifyUrl"));
            alipayTradeAppPayRequest.setReturnUrl(params.get("notifyUrl"));
            AlipayTradeAppPayResponse alipayTradeAppPayResponse = (AlipayTradeAppPayResponse) defaultAlipayClient.sdkExecute((AlipayRequest) alipayTradeAppPayRequest);
            orderString = alipayTradeAppPayResponse.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("生成订单出错，请检查代码参数,错误信息:{}", orderString);
        }
        return orderString;
    }

    public static Map<String, String> getAlipayResult(HttpServletRequest request) {
        Map<String, String> params = new TreeMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? (valueStr + values[i]) : (valueStr + values[i] + ",");
            }
            params.put(name, valueStr);
        }
        return params;
    }

    public static boolean verify(Map<String, String> params) throws AlipayApiException {
        String alipayPublicKey = ALIPAY_PUBLIC_KEY;
        String charset = CHARSET;
        String signType = SIGNTYPE;
        boolean signVerified = false;
        signVerified = AlipaySignature.rsaCheckV1(params, alipayPublicKey, charset, signType);
        return signVerified;
    }

    public static boolean check(Map<String, String> params) {
        String seller_id = params.get("seller_id");
        String app_id = params.get("app_id");
        if (!app_id.equals(APPID))
            return false;
        return true;
    }

    public static String getOutTradeNo() {
        int r1 = (int) (Math.random() * 10.0D);
        int r2 = (int) (Math.random() * 10.0D);
        long now = System.currentTimeMillis();
        String id = String.valueOf(r1) + String.valueOf(r2) + String.valueOf(now);
        return id;
    }
}

